package com.stedu.service.impl;

import com.stedu.bean.Book;
import com.stedu.bean.Classify;
import com.stedu.bean.ClassifyWithBookCount;
import com.stedu.exception.SteduException;
import com.stedu.mapper.ClassifyMapper;
import com.stedu.service.ClassifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ClassifyServiceImpl implements ClassifyService {
    @Autowired
    private ClassifyMapper classifyMapper;
    @Override
    @CacheEvict(value = "book_back", key = "'classifyAll'")
    public boolean insertClassify(Classify classify) throws SteduException {
        if (classifyMapper.selectCname(classify.getCname()) != null){
            throw new SteduException("已有该分类，不能添加");
        }
        return classifyMapper.insertClassify(classify) == 1;
    }

    @CacheEvict(value = "book_back", key = "'classifyAll'")
    @Override
    public boolean deleteClassify(Integer cid) {
        return classifyMapper.deleteClassify(cid) == 1;
    }

    @CacheEvict(value = "book_back", key = "'classifyAll'")
    @Override
    public boolean updateClassify(Classify classify) {
        return classifyMapper.updateClassify(classify) == 1;
    }

    @Override
    public Classify selectCname(String cname) {
        return classifyMapper.selectCname(cname);
    }

    @Cacheable(value = "book_back", key = "'classifyAll'", unless = "#result == null || #result.size() == 0")
    @Override
    public List<Book> selectAll() {
        return classifyMapper.selectAll();
    }

    @Override
    public ClassifyWithBookCount selectByIdAndName(Integer cid, String cname) {
        return classifyMapper.selectByIdAndName(cid, cname);
    }

    @Override
    public Classify selectBookWithClassifies(String cname) {
        return classifyMapper.selectBookWithClassifies(cname);
    }
}
